﻿using HZY.Framework.DependencyInjection;
using Long.BLL;
using Long.Helper;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Long.SpraySCADA
{
    public partial class PageUserManage : UIPage, ISingletonSelfDependency
    {
        private readonly UserManager _userManager;
        public PageUserManage(UserManager userManager)
        {
            InitializeComponent();
            _userManager = userManager;

            this.cb_Auth.Items.AddRange(Enum.GetNames(typeof(SystemEnums.UserRole)));
            this.cb_Auth.SelectedIndex = 0;
        }

        /// <summary>
        /// UI 键入验证
        /// </summary>
        /// <returns></returns>
        private bool VaildInput()
        {
            if (this.txt_UserName.Text.IsNullOrEmpty())
            {
                UIMessageTip.ShowWarning("用户名不能为空！");
                return false;
            }
            if (this.txt_Password.Text.IsNullOrEmpty())
            {
                UIMessageTip.ShowWarning("密码不能为空！");
                return false;
            }
            if (this.txt_EnterPassword.Text.IsNullOrEmpty())
            {
                UIMessageTip.ShowWarning("确认密码不能为空！");
                return false;
            }
            if (this.txt_Password.Text != this.txt_EnterPassword.Text)
            {
                UIMessageTip.ShowWarning("两次密码输入不一致！");
                return false;
            }

            if (this.cb_Auth.SelectedIndex == -1)
            {
                UIMessageTip.ShowWarning("请选择用户权限！");
                return false;
            }
            return true;
        }


        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_AddUser_Click(object sender, EventArgs e)
        {
            //验证，必有信息是否存在，输入合规
            if (!VaildInput())
            {
                return;
            }

            //添加用户
            UserAddDto? userAddDto = new UserAddDto()
            {
                UserName = this.txt_UserName.Text,
                UserPassword = this.txt_Password.Text,
                Role = this.cb_Auth.SelectedItem.ToString()
            };
            BaseResult result = await _userManager.AddUserAsyncManager(userAddDto);
            if (result.ResultStatus == SystemEnums.ResultStatus.Success)
            {
                UIMessageTip.ShowOk("添加用户成功！");
                LogExtension.ShowMessage("添加用户成功！", Microsoft.Extensions.Logging.LogLevel.Information);

                await LoadData();
            }
            else
            {
                UIMessageTip.ShowError(result.Msg);
                LogExtension.ShowMessage("添加用户失败！", Microsoft.Extensions.Logging.LogLevel.Information);
            }
        }


        private async void PageUserManage_Load(object sender, EventArgs e)
        {
            bool result = await LoadData();
            if (!result)
            {
                UIMessageTip.ShowError("加载数据失败！");
            }
        }

        private async Task<bool> LoadData()
        {
            BaseResult<UserQueryResultDto> result = await _userManager.GetUserListAsyncManager();
            if (result.ResultStatus == SystemEnums.ResultStatus.Success)
            {
                this.dgv_User.DataSource = result.Data;
                this.dgv_User.Refresh();
                return true;
            }
            return false;
        }

        private void dgv_User_SelectIndexChange(object sender, int index)
        {
            //获取选中行的数据，并显示在控件上
            DataGridViewRow row = this.dgv_User.Rows[index];
            this.txt_UserName.Text = row.Cells["UserName"].Value.ToString();
            this.txt_Password.Text = row.Cells["UserPassword"].Value.ToString();
            this.txt_EnterPassword.Text = row.Cells["UserPassword"].Value.ToString();
            this.cb_Auth.SelectedItem = row.Cells["Role"].Value.ToString();
        }

        private async void btn_Update_Click(object sender, EventArgs e)
        {
            //验证，必有信息是否存在，输入合规
            if (!VaildInput())
            {
                return;
            }

            UserUpdateDto updateDto = new UserUpdateDto()
            {
                Id = Convert.ToInt32(this.dgv_User.CurrentRow.Cells["Id"].Value),
                UserName = this.txt_UserName.Text,
                UserPassword = this.txt_Password.Text,
                Role = this.cb_Auth.SelectedItem.ToString()
            };

            BaseResult res = await _userManager.UpdateUserAsyncManager(updateDto);
            if (res.ResultStatus == SystemEnums.ResultStatus.Success)
            {
                UIMessageTip.ShowOk("更新用户成功！");
                LogExtension.ShowMessage("更新用户成功！", Microsoft.Extensions.Logging.LogLevel.Information);

                await LoadData();
            }
            else
            {
                UIMessageTip.ShowError(res.Msg);
                LogExtension.ShowMessage("更新用户失败！", Microsoft.Extensions.Logging.LogLevel.Information);

            }
        }

        private async void btn_Delete_Click(object sender, EventArgs e)
        {
            //判断是否选中
            if (this.dgv_User.CurrentRow == null)
            {
                UIMessageTip.ShowWarning("请先选择要删除的用户！");
                return;
            }

            UserDeleteDto deleteDto = new UserDeleteDto()
            {
                Id = Convert.ToInt32(this.dgv_User.CurrentRow.Cells["Id"].Value)
            };

            BaseResult res = await _userManager.DeleteUserAsyncManager(deleteDto);
            if (res.ResultStatus == SystemEnums.ResultStatus.Success)
            {
                UIMessageTip.ShowOk("删除用户成功！");
                LogExtension.ShowMessage("删除用户成功！", Microsoft.Extensions.Logging.LogLevel.Information);

                await LoadData();
            }
            else
            {
                UIMessageTip.ShowError(res.Msg);
                LogExtension.ShowMessage("删除用户失败！", Microsoft.Extensions.Logging.LogLevel.Information);
            }
        }
        #region 窗体切换卡顿
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams paras = base.CreateParams;
                paras.ExStyle |= 0x02000000;
                return paras;
            }
        }
        #endregion
    }
}
